<template>
    <div class="login">
        <Teleport to=".header">
        <Header title="登录"></Header>
    </Teleport>
    <van-form @failed="failedHandler" @submit="submitHandler" >
        <van-cell-group inset class="login-form">
            <van-field
            v-model="userInfo.loginname"
            name="用户名"
            placeholder="账号名/邮箱/手机号"
            :rules="[{pattern: /^\w{5,12}$/, required: true, message: '请填写合适的用户名' }]"
            />
            <van-field
            v-model="userInfo.password"
            type="password" 
            name="密码"
            placeholder="请输入密码"
            :rules="[{pattern: /^\w{5,12}$/, required: true, message: '请填写合适的密码' }]"
            />
        </van-cell-group>
            <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
            提交
            </van-button>
            <van-button style="margin-top: 20px;" @click="$router.push('/register')" round block type="primary" native-type="submit">
            注册
            </van-button>
        </div>
    </van-form>

    </div>
</template>

<script setup lang="ts">
import Header from '@/components/header.vue'
import { ref } from 'vue';
import { showSuccessToast, showFailToast } from 'vant';
import { loginInfo } from '@/apis/login'
import { useRouter } from 'vue-router';
const $route = useRouter()
interface info {
    loginname:String
    password:String
}
const userInfo = ref<info>({
    loginname: '', password: ''
})
const failedHandler=()=>{
    showFailToast('请填写正确的用户名或密码');
}
const submitHandler=async()=>{
    const res = await loginInfo( userInfo.value)
    console.log(res)
    if(res.code==10011) return

    window.localStorage.setItem('token',res.data.token)
    window.localStorage.setItem('user_id', res.data.userid)

    showSuccessToast(res.message)
    
    setTimeout(() => {
        $route.push('/home')
    }, 1000);
    
}
</script>




<style lang="scss" scoped>
.login{
    display: flex;
    flex-direction: column;
}
.login-form{
background-color: #f6f6f6!important;
}
</style>